package com.jason.digest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jason.digest.bean.SignPojo;
import com.jason.digest.utils.MapSortUtils;
import com.jason.digest.utils.SignUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MyController {

    @RequestMapping("/test")
    public Object test(@RequestParam("name") String name,@RequestParam("value") String value){
        return null;
    }

    @GetMapping("/test2")
    public Object getTest(String sign, HttpServletRequest request){

        HashMap<String, Object> map = new HashMap<>();

        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            map.put(name, request.getParameter(name));
        }

        //排序
        Map<String,Object> map1 = MapSortUtils.sortMapByKey(map);
        //生产签名
        String sign1 = SignUtils.generatorSign(map1);
        if(sign1.equals(sign)){
            return "SUCCESS";
        }
        return "FAIL";
    }

    @PostMapping("/test3")
    public Object postTest(String sign,@RequestBody SignPojo signPojo,HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();

        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            map.put(name, request.getParameter(name));
        }

        Map map2 = JSON.parseObject(JSON.toJSONString(signPojo), new TypeReference<Map>() {
        });
        map.putAll(map2);

        //排序
        Map<String,Object> map1 = MapSortUtils.sortMapByKey(map);

        //生产签名
        String sign1 = SignUtils.generatorSign(map1);
        if(sign1.equals(sign)){
            return "SUCCESS";
        }
        return "FAIL";
    }
}
